package middlewares

import (
	"github.com/gin-gonic/gin"
	"scaffold-demo-go/config"
	"scaffold-demo-go/utils/jwtauth"
	"scaffold-demo-go/utils/logs"
)

func JWTAuth(c *gin.Context) {
	// 除了login和logout之外的所有的接口，都要验证请求是否携带token，并且token是否合法
	requestURL := c.FullPath()
	logs.Deubg(map[string]interface{}{"请求地址": requestURL}, "")
	if requestURL == "/api/auth/logout" || requestURL == "/api/auth/login" {
		logs.Deubg(map[string]interface{}{"请求路径": requestURL}, "登录和退出需要验证token")
		c.Next()
		return
	}
	returnData := config.NewReturnData()
	// 其他接口需要验证token
	// 获取是否携带token
	token := c.Request.Header.Get("Authorization")
	if token == "" {
		// 请求没有携带token
		returnData.Status = 401
		returnData.Message = "无登陆"
		c.JSON(200, returnData)
		c.Abort()
		return
	}
	claims, err := jwtauth.ParseJwt(token)
	if err != nil {
		returnData.Status = 401
		returnData.Message = "token不合法"
		c.JSON(200, returnData)
		c.Abort()
		return
	}
	c.Set("claims", claims)
	c.Next()
}
